<template>
  <div class="container-content">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-descriptions :column="6" border>
            <template #title>
              <div class="container-header">
                {{ `事件研判（编号：${research.eventNo ?? "--"}）` }}
                <div class="close-icon" @click="hanldeGoBack">
                  <el-icon><CircleClose /></el-icon>
                </div>
              </div>
            </template>
            <el-descriptions-item label="事件类型">{{
              research.typeName
            }}</el-descriptions-item>
            <el-descriptions-item label="车牌号">{{
              research.eventPlateno
            }}</el-descriptions-item>
            <el-descriptions-item label="检测车速"
              >{{ research.eventSpeed }}km/h</el-descriptions-item
            >
            <el-descriptions-item label="发生时间">{{
              research.eventCreateTime
            }}</el-descriptions-item>

            <el-descriptions-item label="过车时间">{{
              research.eventPasstime
            }}</el-descriptions-item>
            <el-descriptions-item label="研判时间">{{
              research.eventYpTime ?? "--"
            }}</el-descriptions-item>
            <el-descriptions-item label="研判状态">
              <el-tag size="small">{{ research.eventYpStateName }}</el-tag>
            </el-descriptions-item>

            <el-descriptions-item label="卡口方向">{{
              research.deviceDirection
            }}</el-descriptions-item>
            <el-descriptions-item label="卡口信息">{{
              research.deviceName
            }}</el-descriptions-item>
            <el-descriptions-item label="工地名称">--</el-descriptions-item>
            <el-descriptions-item label="工地地址">--</el-descriptions-item>

            <el-descriptions-item
              style="display: inline-flex; align-items: center"
              class-name="flex-research"
              label="现场照片"
            >
              <el-image
                style="width: 102px; height: 40px"
                :src="research.list.length !== 0 ? research.list[0] : ''"
                :zoom-rate="1.2"
                :previewSrcList="research.list"
                :max-scale="5"
                :min-scale="0.2"
                :initial-index="4"
                fit="cover"
              />
            </el-descriptions-item>
            <el-descriptions-item
              v-if="research.eventCzStateName"
              label="处置状态"
              >{{ research.eventCzStateName }}</el-descriptions-item
            >
            <el-descriptions-item
              v-if="research.transferSource"
              label="转派来源"
              >{{ research.transferSource }}</el-descriptions-item
            >
            <el-descriptions-item
              v-if="research.transferTarget"
              label="转派目标"
              >{{ research.transferTarget }}</el-descriptions-item
            >
            <el-descriptions-item
              v-if="research.eventYpState === 1"
              label="研判意见"
              >{{ research.eventYpyj }}</el-descriptions-item
            >
          </el-descriptions>
          <div
            style="
              padding: 15px 15px 0px;
              display: flex;
              justify-content: space-between;
            "
            v-if="research.eventYpState !== 1"
          >
            <div>
              <el-form :inline="true">
                <el-form-item label="办理区县">
                  <el-tree-select
                    v-model="formData.eventTaskAreaNo"
                    :data="deptOptions"
                    :props="{ label: 'deptName', children: 'children' }"
                    :render-after-expand="false"
                    node-key="areaNo"
                    :check-strictly="true"
                    :check-on-click-node="true"
                    :expand-on-click-node="false"
                    placeholder="请选择区县"
                    @node-click="handleClick"
                  />
                </el-form-item>
                <el-form-item v-if="state.show" label="办理街道">
                  <el-tree-select
                    v-model="formData.eventCzAreano"
                    :data="deptOptionAre"
                    :props="{ label: 'deptName', children: 'children' }"
                    :render-after-expand="false"
                    node-key="areaNo"
                    :check-strictly="true"
                    :check-on-click-node="true"
                    :expand-on-click-node="false"
                    placeholder="请选择街道"
                  />
                </el-form-item>

                <el-form-item label-align="center" label="处理意见">
                  <el-input
                    v-model="formData.eventYpyj"
                    placeholder="请输入处理意见"
                    style="width: 300px"
                  />
                </el-form-item>
              </el-form>
            </div>
            <div v-if="research.eventYpState !== 1 && show">
              <el-button
                style="height: 30px"
                type="warning"
                @click="handleEventJudgeInvalid"
                :disabled="!state.show"
                v-if="!userStore.admin"
                >判定无效</el-button
              >
              <el-button
                style="height: 30px"
                type="success"
                @click="handleEventJudgeValid"
                :disabled="!state.show"
                v-if="!userStore.admin"
                >判定冒装</el-button
              >

              <el-button
                style="height: 30px"
                type="primary"
                @click="handleEventTransfer"
                :disabled="state.show"
                >转派</el-button
              >
              <!-- <el-button
                style="height: 30px"
                type="primary"
                @click="hanldeGoBack"
                >返回</el-button
              > -->
            </div>
          </div>
        </div>
      </template>

      <div style="display: flex; justify-content: space-between">
        <el-form
          :inline="true"
          ref="ruleFormRefGps"
          :model="form"
          class="demo-form-inline"
        >
          <el-form-item prop="time">
            <el-date-picker
              v-model="state.time"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>

          <el-form-item>
            <el-button style="height: 30px" type="primary" @click="onSubmit"
              >查询</el-button
            >
          </el-form-item>
        </el-form>
        <div>
          <el-radio-group @change="handleChangeType" v-model="state.typeMap">
            <el-radio-button :label="1">轨迹展示</el-radio-button>
            <el-radio-button :label="2">GPS展示</el-radio-button>
          </el-radio-group>
        </div>
      </div>
      <!--动画控制-->
      <div :style="{ '--dom': dom }" class="container-map">
        <el-row style="height: 100%" :gutter="10">
          <el-col :span="24 - cMap - rMap - (cMap * rMap ? 0 : 1)">
            <div class="container-map-left">
              <div id="container" v-loading="loading" class="container"></div>
              <div
                v-if="state.path.length !== 0 && state.typeMap === 1"
                class="input-card"
              >
                <div class="input-item">
                  <input
                    type="button"
                    class="btn"
                    value="开始动画"
                    id="start"
                    onclick="startAnimation()"
                  />
                  <input
                    type="button"
                    class="btn"
                    value="暂停动画"
                    id="pause"
                    onclick="pauseAnimation()"
                  />
                </div>
                <div class="input-item">
                  <input
                    type="button"
                    class="btn"
                    value="继续动画"
                    id="resume"
                    onclick="resumeAnimation()"
                  />
                  <input
                    type="button"
                    class="btn"
                    value="停止动画"
                    id="stop"
                    onclick="stopAnimation()"
                  />
                </div>
              </div>
            </div>
          </el-col>
          <!--坐标地图信息-->
          <el-col :span="cMap" v-if="cMap !== 0">
            <div class="container-map-center">
              <el-alert
                :title="`GPS坐标列表(${state.tableData.length}个点)`"
                effect="light"
                type="warning"
                @close="cMap = 0"
              />
              <div
                v-if="state.tableData.lfngth !== 0"
                style="height: calc(100% - 34px)"
              >
                <el-table
                  :data="state.tableData"
                  height="100%"
                  style="width: 100%"
                >
                  <el-table-column label="序号" type="index" width="66" />
                  <el-table-column prop="time" label="时间" />
                  <el-table-column prop="data" label="经纬度" />
                </el-table>
              </div>

              <el-empty v-else :image-size="100" />
            </div>
          </el-col>
          <!--时间线信息-->
          <el-col :span="rMap" v-if="rMap !== 0">
            <div class="container-map-right">
              <div>
                <el-alert
                  title="事件线"
                  effect="light"
                  type="success"
                  @close="rMap = 0"
                />
              </div>
              <el-timeline
                v-if="activities.length !== 0"
                style="margin-top: 10px"
              >
                <el-timeline-item
                  v-for="(activity, index) in activities"
                  :key="index"
                  :color="activity.color || '#0bbd87'"
                  :timestamp="activity.executeNode + activity.executeTime"
                  placement="top"
                >
                  <div>
                    <p v-if="activity.executor">
                      操作人：{{ activity.executor }}
                    </p>

                    <p>处置单位：{{ activity.executeDept }}</p>
                    <p v-if="activity.executeContent">
                      操作意见：{{ activity.executeContent }}
                    </p>
                  </div>
                </el-timeline-item>
              </el-timeline>
              <el-empty v-else :image-size="100" />
            </div>
          </el-col>
          <el-col :span="cMap * rMap ? 0 : 0.5" style="transform: none">
            <div v-if="cMap === 0" class="map-close" @click="cMap = 6">
              <div>
                <!-- <el-icon><DArrowLeft /></el-icon> -->
                坐标列表
              </div>
            </div>
            <div
              v-if="rMap === 0"
              class="map-close"
              style="background-color: #f0f9eb; color: #67ccc3"
              @click="rMap = 6"
            >
              <div>
                <!-- <el-icon><DArrowLeft /></el-icon> -->
                事件线
              </div>
            </div>
          </el-col>
        </el-row>
      </div>
    </el-card>
    <!--研判-->
    <el-dialog v-model="state.dialogFormVisible" title="研判类型" width="500">
      <el-form :model="formData">
        <el-form-item prop="eventYpyjTypeid" label="研判类型">
          <el-select
            v-model="formData.eventYpyjTypeid"
            placeholder="请选择研判类型"
          >
            <el-option
              v-for="(item, index) in event_ypyj_typeid"
              :key="index"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="state.dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleConfirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import AMapLoader from "@amap/amap-jsapi-loader";
import { onMounted, onUnmounted, reactive, ref } from "vue";
import { getAllGridInfo } from "@/api/map/index";

import { useRoute, useRouter } from "vue-router";
import {
  getSiteListByAreaNo,
  getRearchByEventId,
  getEventflowRecord,
  eventJudgeInvalid,
  eventJudgeValid,
  getDeptTree,
  getGpsListByPlateNoAndBeginTimeAndEndTime,
  eventTransfer,
  getRote,
} from "@/api/research/index";
import { ElMessage } from "element-plus";
const url = import.meta.env.VITE_APP_BASE_API + "/common/preview/";
console.log(url);
import { formatDate } from "@/utils/index";
import useUserStore from "@/store/modules/user";
import axios from "axios";
const userStore = useUserStore();
const route = useRoute();
const router = useRouter();
const eventId = route.query.eventId;
const show = route.query.show === "0" ? false : true;
const cMap = ref(6);
const rMap = ref(6);
const markArr = ref([]);
const ruleFormRefGps = ref();
const polygonList = ref([]);
const textList = ref([]);
const formData = reactive({
  eventId: eventId,
  eventCzAreano: "",
  eventTaskAreaNo: "",
  eventYpTypeId: "",
  eventYpyj: "",
  eventYpyjTypeid: "",
});
const loading = ref(false);

/**
 *
 * 无效
 */
const handleEventJudgeInvalid = () => {
  state.dialogFormVisible = true;
};

/**
 * 冒装
 */

const handleEventJudgeValid = () => {
  eventJudgeValid(formData).then((res) => {
    if (res.code === 200) {
      ElMessage.success({
        message: "判定冒装成功",
        type: "success",
      });
      handleRearchByEventId();
      getEventflowRecordArr();
    }
  });
};
/**
 * 转派
 */
const handleEventTransfer = () => {
  eventTransfer({
    eventId: eventId,
    eventTaskAreaNo: formData.eventTaskAreaNo,
    eventYpyj: formData.eventYpyj,
  }).then((res) => {
    ElMessage.success({
      message: "转派成功",
      type: "success",
    });
    handleRearchByEventId();
    getEventflowRecordArr();
    router.go(-1);
  });
};
const handleConfirm = () => {
  eventJudgeInvalid({
    eventId: eventId,
    eventTaskAreaNo: formData.eventTaskAreaNo,
    eventYpyjTypeid: formData.eventYpyjTypeid,
  }).then((res) => {
    if (res.code === 200) {
      ElMessage.success({
        message: "判定无效成功",
        type: "success",
      });
      state.dialogFormVisible = false;
      handleRearchByEventId();
      getEventflowRecordArr();
    }
  });
};
const state = reactive({
  center: [106.56901, 29.55566], // 地图中心点
  point: [106.56901, 29.55566], // 经纬度-lng lat
  map: null, // 地图实例
  marker: null, // 地图icon
  geocoder: null, // 逆解析实例
  address: "", // 地址
  weatherCity: "重庆",
  data: [],
  style: {},
  code: "",
  show: userStore.admin ? false : true,
  time: "",
  tableData: [],
  path: [],
  polyline: null,
  dialogFormVisible: false,
  startMarker: null,
  endMarker: null,
  typeMap: 1,
  manyMarkers: [],
  layer: null,
  passedPolyline: null,
  centerCode: [],
  pathArr: [],
});
const research = ref({
  eventYpState: 1,
  list: [],
});
const dom = ref("");
const activities = ref([]);
const deptOptions = ref(undefined);
const deptOptionAre = ref(undefined);
const form = reactive({
  beginTime: "",
  endTime: "",
  plateNo: "",
});

const handleResize = (entries) => {
  for (const entry of entries) {
    dom.value = entry.target.clientHeight + "px";
  }
};

const hanldeGoBack = () => {
  router.go(-1);
};
const getDeptTreeDesc = (code = 100) => {
  getDeptTree({ deptId: code }).then((res) => {
    if (code !== 100) {
      deptOptionAre.value = res.data;
    } else {
      deptOptions.value = res.data;
    }
  });
};
const handleClick = (data) => {
  formData.eventTaskAreaNo = data.areaNo;
  console.log(data);
  if (!userStore.admin) {
    if (data.deptId !== state.code) {
      state.show = false;
    } else {
      state.show = true;
    }
  }
};
let arr = [
  [116.478935, 39.997761],
  [116.478939, 39.997825],
  [116.478912, 39.998549],
  [116.478912, 39.998549],
  [116.478998, 39.998555],
  [116.478998, 39.998555],
  [116.479282, 39.99856],
  [116.479658, 39.998528],
  [116.480151, 39.998453],
  [116.480784, 39.998302],
  [116.480784, 39.998302],
  [116.481149, 39.998184],
  [116.481573, 39.997997],
  [116.481863, 39.997846],
  [116.482072, 39.997718],
  [116.482362, 39.997718],
  [116.483633, 39.998935],
  [116.48367, 39.998968],
  [116.484648, 39.999861],
];

/**
 * 获取GPS
 */
const getGpsListByPlateNo = () => {
  getGpsListByPlateNoAndBeginTimeAndEndTime(form).then((res) => {
    state.tableData = res.data.map((item, index) => {
      return {
        data: item.longitude + "," + item.latitude,
        time: item.gpsTime,
      };
    });

    state.pathArr = res.data.map((item, index) => {
      let tm =
        index === 0
          ? Math.floor(new Date(item.gpsTime).getTime() / 1000)
          : index + 1;

      return {
        x: Number(item.longitude),
        y: Number(item.latitude),
        sp: Number(item.speed),
        ag: Number(item.direction),
        tm: tm,
      };
    });
    state.path = [];
    res.data.forEach((item) => {
      state.path.push([Number(item.longitude), Number(item.latitude)]);
    });

    if (state.path.length !== 0) {
      state.map.setZoomAndCenter(16, state.path[0]);

      record();
    } else {
      state.map.setZoomAndCenter(16, state.centerCode);
    }
  });
};

const handleChangeType = () => {
  if (state.path.length === 0) {
    return;
  }
  if (state.marker) {
    state.marker.setMap(null);
    state.polyline.setMap(null);
    state.startMarker.setMap(null);
    state.endMarker.setMap(null);
    state.passedPolyline.setMap(null);
    state.marker = null;
    state.polyline = null;
    state.passedPolyline = null;
    state.startMarker = null;
    state.endMarker = null;
  }
  if (state.layer) {
    state.manyMarkers = [];
    state.layer.clear();
    state.layer = null;
  }
  if (state.typeMap === 1) {
    record();
  } else {
    manyMark();
  }
};
/**
 * 轨迹回放
 */
const record = () => {
  if (state.marker) {
    state.marker.setMap(null);
    state.polyline.setMap(null);
    state.startMarker.setMap(null);
    state.endMarker.setMap(null);
    state.passedPolyline.setMap(null);
    state.marker = null;
    state.polyline = null;
    state.passedPolyline = null;
    state.startMarker = null;
    state.endMarker = null;
  }
  let graspRoad;
  AMap.plugin("AMap.MoveAnimation", function () {
    state.marker = new AMap.Marker({
      map: state.map,
      position: state.path[0],
      icon: "https://a.amap.com/jsapi_demos/static/demo-center-v2/car.png",
      offset: new AMap.Pixel(-13, -26),
    });

    var startIcon = new AMap.Icon({
      // 图标尺寸
      size: new AMap.Size(25, 34),
      // 图标的取图地址
      image: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png",
      // 图标所用图片大小
      imageSize: new AMap.Size(135, 40),
      // 图标取图偏移量
      imageOffset: new AMap.Pixel(-9, -3),
    });

    state.startMarker = new AMap.Marker({
      map: state.map,
      position: state.path[0],

      icon: startIcon,
      offset: new AMap.Pixel(-13, -30),
    });

    var endIcon = new AMap.Icon({
      size: new AMap.Size(25, 34),
      image: "//a.amap.com/jsapi_demos/static/demo-center/icons/dir-marker.png",
      imageSize: new AMap.Size(135, 40),
      imageOffset: new AMap.Pixel(-95, -3),
    });
    state.endMarker = new AMap.Marker({
      map: state.map,
      position: state.path[state.path.length - 1],

      icon: endIcon,
      offset: new AMap.Pixel(-13, -30),
    });

    // state.map.add(state.polyline);
    // if (!graspRoad) {
    //   new AMap.plugin("AMap.GraspRoad", () => {
    //     graspRoad = new AMap.GraspRoad();
    //   });
    // }
    // console.log(state.pathArr);
    // graspRoad.driving(state.pathArr, function (error, result) {
    //   console.log(error);
    //   if (!error) {
    //     var path2 = [];
    //     var newPath = result.data.points;
    //     for (var i = 0; i < newPath.length; i += 1) {
    //       path2.push([newPath[i].x, newPath[i].y]);
    //     }
    //     console.log(path2);
    //     var newLine = new AMap.Polyline({
    //       path: path2,
    //       // map: state.map,
    //       strokeWeight: 8,
    //       strokeOpacity: 0.8,
    //       strokeColor: "#0091ea",
    //       showDir: true,
    //     });
    //     state.map.add(newLine);
    //     state.map.setFitView();
    //   }
    // });

    let arr = [];

    axios
      .get(
        `https://restapi.amap.com/v3/direction/driving?origin=${
          state.path[0]
        }&destination=${
          state.path[state.path.length - 1]
        }&waypoints=${state.path.join(
          ";"
        )}&extensions=all&output=json&key=3a3aeee9d5516c964aff56bc2a0b00c7`
      )
      .then((res) => {
        console.log(res);
        var steps = res.data.route.paths[0].steps;
        for (let i = 0; i < steps.length; i++) {
          const data = steps[i].polyline.split(";");
          data.forEach((item) => {
            arr.push([Number(item.split(",")[0]), Number(item.split(",")[1])]);
          });
        }
        state.polyline = new AMap.Polyline({
          path: arr,
          strokeOpacity: 0.8,
          strokeColor: "#28F", //线颜色
          strokeWeight: 6, //线宽
          showDir: true,
        });
        state.map.add(state.polyline);
      });

    state.passedPolyline = new AMap.Polyline({
      map: state.map,
      strokeColor: "#AF5", //线颜色
      strokeWeight: 6, //线宽
    });

    state.marker.on("moving", function (e) {
      state.passedPolyline.setPath(e.passedPath);
      state.map.setCenter(e.target.getPosition(), true);
    });
    window.startAnimation = function startAnimation() {
      state.marker.moveAlong(arr, {
        // 每一段的时长
        duration: 10, //可根据实际采集时间间隔设置
        // JSAPI2.0 是否延道路自动设置角度在 moveAlong 里设置
        autoRotation: true,
      });
    };
    window.pauseAnimation = function () {
      state.marker.pauseMove();
    };

    window.resumeAnimation = function () {
      state.marker.resumeMove();
    };
    window.stopAnimation = function () {
      state.marker.stopMove();
    };
  });
};
const manyMark = () => {
  // 创建 AMap.LabelsLayer 图层
  state.layer = new AMap.LabelsLayer({
    zooms: [3, 20],
    zIndex: 1000,
    collision: false,
  });

  // 将图层添加到地图
  state.map.add(state.layer);
  state.manyMarkers = [];

  var icon = {
    type: "image",
    image: "https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png",
    size: [9, 12],
    anchor: "bottom-center",
  };

  for (var i = 0; i < state.path.length; i++) {
    var curPosition = state.path[i];
    var curData = {
      position: curPosition,
      icon,
    };

    var labelMarker = new AMap.LabelMarker(curData);

    state.manyMarkers.push(labelMarker);

    // 给marker绑定事件
    labelMarker.on("mouseover", function (e) {
      var position = e.data.data && e.data.data.position;

      if (position) {
        normalMarker.setContent(
          '<div class="amap-info-window">' +
            position +
            '<div class="amap-info-sharp"></div>' +
            "</div>"
        );
        normalMarker.setPosition(position);
        state.map.add(normalMarker);
      }
    });

    labelMarker.on("mouseout", function () {
      state.map.remove(normalMarker);
    });
  }

  // 一次性将海量点添加到图层
  state.layer.add(state.manyMarkers);

  // 普通点
  var normalMarker = new AMap.Marker({
    anchor: "bottom-center",
    offset: [0, -15],
  });
};
let observer = null;
onMounted(() => {
  initMap().then((res) => {
    getGridInfoListData();
    handleRearchByEventId();
    getSiteListByAreaNoList();
    getEventflowRecordArr();
    let observer = new ResizeObserver(handleResize);
    observer.observe(document.querySelector(".el-card__header"));
  });
});
getDeptTreeDesc();
onUnmounted(() => {
  // 在组件销毁前取消观察
  state.map?.destroy();
  if (observer) {
    observer.disconnect();
  }
});
const { proxy } = getCurrentInstance();

const { event_ypyj_typeid } = proxy.useDict(
  "event_ypyj_typeid" //研判状态
);

/**
 * 获取详情
 */
const handleRearchByEventId = () => {
  getRearchByEventId({ eventId: eventId }).then((res) => {
    research.value = res.data;
    formData.eventTaskAreaNo = res.data.eventTaskAreano;
    state.code = Number(res.data.eventTaskAreano.substring(3, 6));
    state.centerCode = [res.data.deviceX, res.data.deviceY];
    form.plateNo = res.data.eventPlateno;
    // 创建一个新的日期对象来表示当前时间
    let currentTime = new Date(res.data.eventPasstime);
    // 将当前时间加上1小时（60分钟 * 60秒）
    currentTime.setMinutes(currentTime.getMinutes() - 60);
    let time = formatDate(currentTime);
    state.time = [time, res.data.eventPasstime];
    form.beginTime = time;
    form.endTime = res.data.eventPasstime;
    if (research.value.ztcEventfileList.length !== 0) {
      research.value.list = research.value.ztcEventfileList.map((item) => {
        return url + item.eventfilePath;
      });
    }
    getDeptTreeDesc(Number(res.data.eventTaskAreano.substring(3, 6)));
    getGpsListByPlateNo();
    addMarkere(res.data.deviceX, res.data.deviceY, res.data.deviceName);
  });
};
const onSubmit = () => {
  form.beginTime = state.time[0];
  form.endTime = state.time[1];
  getGpsListByPlateNo();
};
function addMarkere(x, y, name) {
  let startIcon = new AMap.Icon({
    // 图标尺寸
    size: new AMap.Size(26, 29),
    // 图标的取图地址
    image:
      "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
    // 图标所用图片大小
    imageSize: new AMap.Size(26, 29),
    // 图标取图偏移量
    imageOffset: new AMap.Pixel(0, 0),
  });
  let marker = new AMap.Marker({
    icon: startIcon,

    position: [x, y],
    offset: new AMap.Pixel(-13, -30),
  });
  marker.setLabel({
    direction: "bottom",
    offset: new AMap.Pixel(0, 6), //设置文本标注偏移量
    content: `<div class='info'>${name}</div>`, //设置文本标注内容
  });
  marker.setMap(state.map);
}
/**
 * 获取部门数据
 */

/**
 *记录
 */
const getEventflowRecordArr = () => {
  getEventflowRecord({ eventNo: route.query.eventNo }).then((res) => {
    activities.value = res.data;
  });
};
//获取行政区域地图电子围栏 多个行政区域 这样写才不卡
const getGridInfoListData = () => {
  const map = localStorage.getItem("map");
  if (userStore.map.length !== 0 || map) {
    const data = (map && JSON.parse(map)) || userStore.map;
    data.forEach((item) => {
      let polygonItem = addPolygon(item.geometry.coordinates, item.gridStyle);
      polygonList.value.push(polygonItem);

      let textItem = addText(item.gridName, item.center.coordinates);
      textList.value.push(textItem);
    });
    if (polygonList.value.length !== 0 && textList.value.length !== 0) {
      state.map.add(polygonList.value);
      state.map.add(textList.value);
    }
  }
};
const getSiteListByAreaNoList = () => {
  getSiteListByAreaNo({ areaNo: 50 }).then((res) => {
    const data = res.data;
    if (data.length !== 0) {
      data
        .filter((item) => item.siteX && item)
        .forEach((item) => {
          let mark = addMark(item.siteX, item.siteY);
          markArr.value.push(mark);
        });
    }

    if (markArr.value.length !== 0) {
      state.map.add(markArr.value);
    }
  });
};
/**
 * DOM初始化完成进行地图初始化
 */
const initMap = () => {
  return new Promise((resolve) => {
    AMapLoader.load({
      key: "daf47c0ee853a30ffa8260c6491a1b0a", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      // 需要使用的的插件列表
      plugins: [
        "AMap.Geocoder", // 逆向地理解码插件
        "AMap.Marker", // 点标记插件
      ],
    })
      .then((AMap) => {
        state.map = new AMap.Map("container", {
          viewMode: "2D", // 地图视图模式，默认为‘2D’，可选’3D’，选择‘3D’会显示 3D 地图效果。
          zoom: 12, // 地图显示的缩放级别
          center: state.center, // 初始化地图中心点位置
        });
        // 如果父组件传入了有效值 回显一个icon
        if (state.point.length > 0) {
          // addMarker(AMap);
        }

        // state.map.on("click", (e) => {
        //   state.point = [e.lnglat.lng, e.lnglat.lat];
        //   addMarker(AMap);
        //   // 获取地址
        // });

        resolve();
      })
      .catch((e) => {
        // message.error(e);
      });
  });
};
const m = new URL("./mark.png", import.meta.url).href;

const addMark = (x, y) => {
  let startIcon = new AMap.Icon({
    // 图标尺寸
    size: new AMap.Size(26, 29),
    // 图标的取图地址
    image: m,
    // 图标所用图片大小
    imageSize: new AMap.Size(26, 29),
    // 图标取图偏移量
    imageOffset: new AMap.Pixel(0, 0),
  });
  let startMarker = new AMap.Marker({
    position: new AMap.LngLat(x, y),
    icon: startIcon,
    offset: new AMap.Pixel(-13, -30),
  });
  startMarker.on("mouseover", () => {});
  return startMarker;
};
/**
 * 增加点标记
 * @param AMap AMap
 */
const addMarker = (AMap) => {
  // 清除其他icon
  if (state.marker) {
    state.marker.setMap(null);
    state.marker = null;
  }
  // 重新渲染icon
  state.marker = new AMap.Marker({
    icon: "//a.amap.com/jsapi_demos/static/demo-center/icons/poi-marker-default.png",
    size: new AMap.Size(53, 68), // 图标大小
    imageSize: new AMap.Size(53, 68),
    position: state.point, // icon经纬度
    offset: new AMap.Pixel(-28, -60), // icon中心点的偏移量
  });
  state.marker.setMap(state.map); // 设置icon
};

const addText = (text, center) => {
  let _text = new AMap.Text({
    text: text,
    anchor: "center", // 设置文本标记锚点
    cursor: "pointer",
    style: {
      "margin-bottom": "1rem",
      "border-radius": ".25rem",
      background: "rgba(255, 255, 255, 0.7)",
      minWidth: "5rem",
      "border-width": 0,
      "text-align": "center",
      "font-size": "13.0px",
      "font-weight": "600",
      color: "#000",
    },
    position: center,
  });

  return _text;
};
/**
 * 将经纬度转换为地址
 * @param AMap AMap
 */
const addPolygon = (data, style) => {
  const polygon = new AMap.Polygon({
    path: data,
    fillColor: style.gridFillcolor,
    strokeOpacity: 1,
    fillOpacity: 0.3,
    strokeColor: style.gridStrokecolor,
    strokeWeight: 1,
    cursor: "pointer",
    bubble: true,
    // strokeStyle: "dashed",
    strokeDasharray: [5, 5],
  });
  polygon.on("mouseover", () => {
    polygon.setOptions({
      fillOpacity: 0.7,
      fillColor: style.gridFillcolor,
    });
  });
  polygon.on("mouseout", () => {
    polygon.setOptions({
      fillOpacity: 0.3,
      fillColor: style.gridFillcolor,
    });
  });
  return polygon;
  // polygon.value.setMap(state.map);
};
</script>

<style lang="scss" scoped>
.container-content {
  width: 100%;
  height: calc(100vh);
  padding: 10px 20px;
  box-sizing: border-box;
}
.container-header {
  background: linear-gradient(45deg, #1275ca, #fff);
  padding: 14px 30px 14px 15px;
  color: #fff;
  position: relative;
  .close-icon {
    color: #1275ca;
    font-size: 22px;
    position: absolute;
    right: 10px;
    top: 0;
    padding: 10px 10px;
    cursor: pointer;
    z-index: 1;
  }
}
.container {
  position: relative;
  width: 100%;
  height: calc(100%);
  border: 1px solid #ececec;
}
.container-map {
  width: 100%;
  height: calc(100vh - var(--dom) - 100px);
  // display: flex;
  // justify-content: space-between;
}

.container-map-left {
  // width: calc(50%);
  height: 100%;
  position: relative;
}
.container-map-center {
  // width: 24%;
  min-width: 300px;
  height: 100%;
  border: 1px solid #e4e7ed;
}
.container-map-right {
  // width: 24%;
  min-width: 300px;
  height: 100%;
  border: 1px solid #e4e7ed;
  overflow-y: auto;
}
.map-close {
  cursor: pointer;
  writing-mode: vertical-rl;
  background-color: #fdf6ec;
  color: #eaa23c;
  padding: 10px 2px;
  border: 1px solid #ebeef5;
  font-size: 12px;
  border-radius: 4px;
  margin-top: 10px;
  &:nth-child(2) {
    background-color: #f0f9eb;
    color: #67ccc3;
  }
}
.box-card {
  height: 100%;
}

:deep(.el-input) {
  width: auto;
}

:deep(.el-descriptions__cell:has(.flex-research)) {
  display: inline-flex;
  align-items: center;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  text-align: center;
}
:deep(
    .el-descriptions__body
      .el-descriptions__table
      .is-bordered
      .el-descriptions__cell
  ) {
  padding: 6px 8px;
  // > .el-descriptions__label {
  //   font-weight: 600;
  //   color: #1778cb;
  // }
}
:deep(.el-descriptions__body) {
  margin-bottom: 10px;
}

.info {
  position: relative;
  margin: 0;
  top: 0;
  right: 0;
  min-width: 0;
}

.input-card {
  position: absolute;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  min-width: 0;
  word-wrap: break-word;
  background-color: rgba(255, 255, 255, 0.2);
  background-clip: border-box;
  border-radius: 0.25rem;
  width: 12rem;
  border-width: 0;
  border-radius: 0.4rem;
  box-shadow: 0 2px 6px 0 rgba(114, 124, 245, 0.5);
  -ms-flex: 1 1 auto;
  flex: 1 1 auto;
}
.btn {
  display: inline-block;
  font-weight: 400;
  text-align: center;
  white-space: nowrap;
  vertical-align: middle;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  border: 1px solid transparent;
  transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out,
    border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out;
  background-color: transparent;
  background-image: none;
  color: #25a5f7;
  border-color: #25a5f7;
  line-height: 1.5;
  border-radius: 1rem;
  -webkit-appearance: button;
  cursor: pointer;
}

.btn:hover {
  color: rgb(255, 255, 255);
  background-color: #25a5f7;
  border-color: #25a5f7;
}

.btn:hover {
  text-decoration: none;
}

.input-item {
  position: relative;
  display: -ms-flexbox;
  display: flex;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
  -ms-flex-align: center;
  align-items: center;
  justify-content: space-around;
  width: 100%;
  height: 2.6rem;
}
:deep(.el-image__preview) {
  cursor: zoom-in;
}
:deep(.el-descriptions__body) {
  padding: 0 15px 0;
}
:deep(.el-descriptions__title) {
  width: 100%;
}
:deep(.el-card__header) {
  padding: 0px !important;
}
:deep(.el-timeline) {
  padding-left: 1.2em;
}
:deep(.el-col) {
  transition: all 0.3s ease-out;
  height: 100%;
}
</style>
